﻿// 全局命名空间
var mobileU = {
    author : 'mobileU',
    version: '1.0',
    //keysina:'2297947057',//sina-key
    //keyrenren:'66afa924320a4153b90e89a083693c38',//renren-key
    //keytengxun:'801473283',//tengxun-key
    //urlprefix:'http://211.154.164.10/nwap/apply/',//正式
    //urlrenrenprefix:'http://app.wecash.net/nwap/apply/',//正式
    //urlsina:'https://api.weibo.com/oauth2/authorize?client_id=2297947057',//正式
    //urltengxun:'https://open.t.qq.com/cgi-bin/oauth2/authorize?client_id=801473283',//正式
    //urlrenren:'https://graph.renren.com/oauth/authorize?client_id=66afa924320a4153b90e89a083693c38',//正式


    platfrom:(function(){
        return !!navigator.userAgent.match(/(i[^;]+\;(U;)? CPU.+Mac OS X)/)?'ios':'android';
    }())
};

mobileU.Event = {
    orientationEvent:("onorientationchange" in window) ? "orientationchange resize" : "resize",
    click :$.support.touch ?"tap":"click"
}


// 工具包
mobileU.utils = {
	getParameterByName : function(param, url) {
		url= url||location.href
		var match = RegExp('[?&]' + param + '=([^&]*)').exec(url);
		return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
	},
	setParam : function (name,value){
		localStorage.setItem(name,value);
	},
	getParam : function(name){
		var urlPara = this.getParameterByName(name,location.href);
		urlPara&&localStorage.setItem(name,urlPara);
		return localStorage.getItem(name);
	},

	getBasicPara : function(){
		var para = {};
        para.cache = (new Date().getTime());
		return para;
	},
	getWebSiteAPI : function(){
		return mobileU.webSiteAPI;
	},
    getMailAPI : function(){
        return mobileU.webMailAPI;
    },

	//获取cookie
	getCookie : function(c_name){
		var arr,reg=new RegExp("(^| )"+c_name+"=([^;]*)(;|$)");
		if((arr=document.cookie.match(reg)).length>=2)
			return unescape(arr[2]);
		else
			return null;
	},
	//取消事件冒泡
	stopEvent : function(e){
		e.stopPropagation?e.stopPropagation():e.cancelBubble=true;
		e.preventDefault?e.preventDefault():e.returnValue=false;
	},
	fixedStrLen : function(str,len){
		return str.length>len?str.substring(0,len)+"...":str;
	}, 
	//替换手机号中间四位为*,替换信用卡号除前四位与后四位以外的数字为*
	replaceStr2 : function(str,before){ 
		var len=str.length,temp='*',stm='*';
		if(len>9){
			var strtemp=str.substring(before,len-5);
			for(var i=0;i<strtemp.length;i++){stm+=temp;}
			return str.substring(0,before)+stm+str.substring(len-4,len); 
		}else{
			return str;
		}
	},

	//截取字符串长度，支持中英文混合
	subString : function(str, len, hasDot)
	{
		var newLength = 0;
		var newStr = "";
		var chineseRegex = /[^\x00-\xff]/g;
		var singleChar = "";
		var strLength = str.replace(chineseRegex,"**").length;
		for(var i = 0;i < strLength;i++){
			singleChar = str.charAt(i).toString();
			if(singleChar.match(chineseRegex) !== null){
				newLength += 2;
			}else{
				newLength++;
			}
			if(newLength > len){
				break;
			}
			newStr += singleChar;
		}

		if(hasDot && strLength > len){
			newStr += "...";
		}
		return newStr;
	},
    //保留2位小数
    subNum : function(str)
    {
        var f_x = Math.round(str* 100) / 100;
        var s_x = f_x.toString();
        var pos_decimal = s_x.indexOf('.');
        if (pos_decimal < 0) {
            pos_decimal = s_x.length;
            s_x += '.';
        }
        while (s_x.length <= pos_decimal + 2) {
            s_x += '0';
        }
        return s_x;
    },

	ajaxRender : function($dom,url,para,$tpl,conf){
		$.post(url,para,function(data) {
			data = $.parseJSON(data);
			if(conf&&conf.isappend&&(data.errorNo===0||data.errorNo==='0')){
				$dom.append(_.template($tpl.html(), {data:data,para:para}, {variable: 'rc'}));
			}else{
                if(conf&&conf.loaddir){
                    $dom[conf.loaddir==='up'?'prepend':'append'](_.template($tpl.html(), {data:data,para:para}, {variable: 'rc'}));
                }else{
                    $dom.html(_.template($tpl.html(), {data:data,para:para}, {variable: 'rc'}));
                }

			}
			if(conf&&_.isFunction(conf.succeful)){
				conf.succeful($dom,data);
			}
		});
	},
    
    ajaxGetRender : function($dom,url,para,$tpl,conf){
        $.getJSON(url,para,function(data) {
            if(conf&&conf.isappend&&(data.errorNo===0||data.errorNo==='0')){
                $dom.append(_.template($tpl.html(), {data:data,para:para}, {variable: 'rc'}));
            }else{
                if(conf&&conf.loaddir){
                    $dom[conf.loaddir==='up'?'prepend':'append'](_.template($tpl.html(), {data:data,para:para}, {variable: 'rc'}));
                }else{
                    $dom.html(_.template($tpl.html(), {data:data,para:para}, {variable: 'rc'}));
                }

            }
            if(conf&&_.isFunction(conf.succeful)){
                conf.succeful($dom,data);
            }
        });
    },

	initheader:function(){
        var width = window.innerWidth,
            height = window.innerHeight,
            $iscroll = $("#iscroll");
        $iscroll.css({
            'height': 1*(height-0)
        });
        $('#page').css({"padding-top":height*0,"height":height});
        $("#page").off(mobileU.Event.click,'.t-close').on(mobileU.Event.click,'.t-close', function(e) {
        	utils.closePage();
    	});

        $('body').on(mobileU.Event.click,function(e){
            if($(e.target).attr("id")=='page'){
                utils.closePage();
            }

        });

        //网络监测
        // $(window).on("online",function(){
        //     location.reload();
        // }).on("offline",function(){
        //     utils.popMsg('网络中断，请检查您的网络连接');
        // })

	},
    online:function(){
        location.reload();
    },
    offline:function(){
        utils.popMsg('网络中断，请检查您的网络连接');
    },
    //行为日志
    storeWecashLocal:function(obj){
        if(!obj) return;
        var key = "wecashLocal";
        var custId = localStorage.getItem("wecash_custId");
        if(custId!=null)
        {
            var objlistStr = localStorage.getItem(key);
            var objlist = JSON.parse(objlistStr)||[];
                obj.custid = custId;
                obj.triggertime = new Date().getTime()+'';
                obj.useragent = navigator.userAgent;
                objlist.push(obj); 
            localStorage.setItem(key,JSON.stringify(objlist));
        }
    },
    getWecashFromLocal:function(){
        var key = "wecashLocal";
        var objlistStr = localStorage.getItem(key);
        return JSON.parse(objlistStr);
    },
    getWecashItemById:function(){
        var list = this.getWecashFromLocal();
        if(list&&list.length>0){
            return JSON.stringify(list);
        }else{
            return null;
        }
    },
    //获取时间差
    getTimeDiff : function(datetime1,datetime2)
    {
        var diff=datetime2-datetime1;
        if(diff<0)
        {
            diff=diff*-1;
        }
        return Math.round(diff/1000);
    },
    //提交日志
    postLog : function()
    {
        
        var wecashStr=this.getWecashItemById();
        var para = utils.getBasicPara();
            para.datastr = wecashStr;
            
        $.post(mobileU.webLogAPI+'behaviorAnalysis/wechat',para,function(data){
            data = $.parseJSON(data);
            if(data&&data.success==='1'){
               //提交成功
              localStorage.removeItem("wecashLocal");//删除已提交的日志数据
            }
        },function(error) {
            alert('提交出错了');
        });
    }, 

    //页面跳转日志-进入
    wecashPageInit:function(obj){
        if(!obj) return;
        var custId = localStorage.getItem("wecash_custId");
        if(custId!=null)
        {
            var objlist = [];
                obj.custid = custId;
                obj.useragent = navigator.userAgent;
                obj.reqtype = 0;
                objlist.push(obj);                 
            var wecashStr = JSON.stringify(objlist);

            var para = utils.getBasicPara();
                para.datastr = wecashStr;
                
            $.post(mobileU.webLogAPI+'pathAnalysis/wechat',para,function(data){
                data = $.parseJSON(data);
                if(data&&data.success==='1'){
                   //提交成功
                }
            },function(error) {
                alert('提交出错了');
            });
        }
    },
    //页面跳转日志-离开
    wecashPageEnd:function(obj){
        if(!obj) return;
        var custId = localStorage.getItem("wecash_custId");
        if(custId!=null)
        {
            var objlist = [];
                obj.custid = custId;
                obj.useragent = navigator.userAgent;
                obj.reqtype = 1;
                objlist.push(obj);                 
            var wecashStr = JSON.stringify(objlist);

            var para = utils.getBasicPara();
                para.datastr = wecashStr;
                
            $.post(mobileU.webLogAPI+'pathAnalysis/wechat',para,function(data){
                data = $.parseJSON(data);
                if(data&&data.success==='1'){
                   //提交成功
                }
            },function(error) {
                alert('提交出错了');
            });
        }
    },

    popFailMsg:function(inputname,buttonname){
        //$("#"+buttonname).hide();
        $("#"+inputname).text('图片上传失败');
        //setTimeout(function(){$("#"+inputname).text('');$("#"+buttonname).show();},2000);
    },
    popSuccessMsg:function(inputname,buttonname){
        //$("#"+buttonname).hide();
        $("#"+inputname).text('图片上传成功');
    },
    
    showDleStyle:function(inputname){
        var inputname1=inputname+'1';
        $("#iscroll").on('keyup','#'+inputname,function(){
            var $this = $(this);
            var content = $this.val();
            if(content.length>0){
                $("#"+inputname1).show();
            }
            else{
                $("#"+inputname1).hide();
            }   
        }).on('focus','#'+inputname,function(){
            $("#"+inputname1).show();
        }).on(mobileU.Event.click,'#'+inputname1,function(){
            $("#"+inputname).val('');
            $("#"+inputname1).hide();
        }).on('blur','#'+inputname,function(){
            setTimeout(function(){$("#"+inputname1).hide()},200);
            //$("#"+inputname1).hide();
        });
    },
    maskBankCardNo : function(cardNo) {
      //保留首4位, 尾4位, 其他用*填充
      var maskedCardNo = cardNo.substring(0,4) ;
      for (var i=0;i<cardNo.length-8;i++)
        {
        maskedCardNo += '*' ;
        }
      maskedCardNo += cardNo.substring(cardNo.length-4,cardNo.length)
      return maskedCardNo ;
    },
    getpara:function(paras){
         var url = location.href;  
         var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");  
         var paraObj = {}  
         for (i = 0; j = paraString[i]; i++) {  
             paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);  
         }  
         var returnValue = paraObj[paras.toLowerCase()];  
         if (typeof(returnValue) == "undefined") {  
             return "";  
         } else {  
            //过滤#
            if(returnValue.indexOf("#")>-1)
            {
                returnValue=returnValue.substring(0,returnValue.length-1);
            }
             return returnValue;  
         }  
    }

};

// 业务控制中心，需应用实现
var utils = mobileU.utils;
